package com.sansui.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sansui.blog.dao.*;
import com.sansui.blog.pojo.*;
import com.sansui.blog.pojo.sys.SysEmail;
import com.sansui.blog.pojo.sys.SysEmailLog;
import com.sansui.blog.service.CommentService;
import com.sansui.blog.utils.JsonUtil;
import com.sansui.blog.utils.SendEmail;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @name: CommentServiceImpl
 * @author: Sansui
 * @Software: IDEA
 * @Blog: https://www.cnblogs.com/sansui6/
 * @date: 2022-04-03 00:51
 **/
@Service
public class CommentServiceImpl implements CommentService {


    @Autowired
    private CommentDao commentDao;
    @Autowired
    private SysEmailDao sysEmailDao;
    @Autowired
    private BlogDao blogDao;
    @Autowired
    private SysInfoDao sysInfoDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private SysEmailLogDao sysEmailLogDao;


//    默认头像地址
    @Value("${comment.avatar}")
    private String avatar;

//    获取ip接口地址
    @Value("${comment.ipApi-url}")
    private String ipApiUrl;

    @Override
    public Integer countcomments() {
        return commentDao.countcomments();
    }

    @Override
    public Integer getCommentCountByBlogId(Long blogId) {
        return commentDao.getCommentCountByBlogId(blogId);
    }

    @Override
    public List<Comment> listCommentByBlogId (Long blogId){

        // 获取父级评论信息
        List<Comment> comments = commentDao.findByBlogIdParentIdNull(blogId);

        for(Comment comment : comments){
            Long commentid = comment.getCommentid();
            //根据父级评论id  获取所属子集评论信息
            List<Comment> childComments = commentDao.findParentIdNotNull(commentid);
            //查询出子评论
            combineChildren(childComments);
            comment.setReplyComments(tempReplys);
            tempReplys = new ArrayList<>();
        }

        return comments;
    }


    @Transactional
    @Override
    public Integer saveComments(Comment comment) {
        try{
            // 头像为空时，默认一个头像
            if(comment.getAvatar()==null || comment.getAvatar()==""){
                comment.setAvatar(avatar);
            }
            // 判断是否存在父级评论
            if(comment.getParentcommentid() != -1){
                Comment comment1 = commentDao.getParentCommentById(comment.getParentcommentid());
                comment.setParentnickname(comment1.getNickname());
                comment.setParentComment(comment1);
            }else {
                comment.setParentcommentid(null);
            }
//            comment.setUpcomment(1);
//            comment.setAdmincomment(1);
            comment.setStatus(1);
            comment.setFlag(1);
            comment.setCreatetime(new Date());

            String ipApi = ipApiUrl+comment.getCommentlocation();
            if("0:0:0:0:0:0:0:1".equals(comment.getCommentlocation())){
                ipApi = ipApiUrl;
            }
            JSONObject jsonObject = JsonUtil.loadJson(ipApi);

            Boolean success = ((Boolean)jsonObject.get("success")).booleanValue();
            if(success){
                if("局域网".equals(String.valueOf(JSON.parseObject(jsonObject.get("info").toString()).get("country")))){
                    comment.setSourcecity("火星");
                }else{
                    comment.setSourcecity(String.valueOf(JSON.parseObject(jsonObject.get("info").toString()).get("prov")));
                }
            }else{
                comment.setSourcecity("火星");
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return commentDao.saveComments(comment);
    }

    @Override
    public void sendEmail(Long blogId,String comment,Long parentcommentid,String nickname,String url) {
        try{
            SysEmail sysEmail = sysEmailDao.getSysEmail();

            Blog blog = blogDao.getCreateUserById(blogId);
            User user = userDao.findByUsername(blog.getCreateUser());
            UserInfo userInfo = userInfoDao.getUserInfoByUserId(user.getUid());
            SysConfig sysConfig = sysInfoDao.getSysInfo();
            String webUrl = sysConfig.getWeburl()+"/blogs/"+blogId;
            String addressee = userInfo.getEmail();

            if(parentcommentid != null){
                Comment  comment1 = commentDao.getParentCommentById(parentcommentid);
                addressee = comment1.getEmail();
            }

            String title = "[博客评论通知]Re:"+blog.getTitle();
            String emailContent = "<div>\n" +
            "    <includetail>\n" +
            "        <div align='center'>\n" +
            "            <div class='open_email' style='margin-left: 8px; margin-top: 8px; margin-bottom: 8px; margin-right: 8px;'>\n" +
            "                <div><br>\n" +
            "                    <span class='genEmailContent'>\n" +
            "<div id='cTMail-Wrap' style='word-break: break-all;box-sizing:border-box;text-align:center;min-width:320px; max-width:660px; border:1px solid #f6f6f6; background-color:#f7f8fa; margin:auto; padding:20px 0 30px; font-family:'helvetica neue',PingFangSC-Light,arial,'hiragino sans gb','microsoft yahei ui','microsoft yahei',simsun,sans-serif'>\n" +
            "<div class='main-content' style=''>\n" +
            "<table style='width:100%;font-weight:300;margin-bottom:10px;border-collapse:collapse'>\n" +
            "<tbody>\n" +
            "<tr style='font-weight:300'>\n" +
            "<td style='width:3%;max-width:30px;'></td>\n" +
            "<td style='max-width:600px;'><h3>博客评论通知</h3>\n" +
            "<p style='height:2px;background-color: #00a4ff;border: 0;font-size:0;padding:0;width:100%;margin-top:20px;'></p>\n" +
            "<div id='cTMail-inner' style='background-color:#fff; padding:23px 0 20px;box-shadow: 0px 1px 1px 0px rgba(122, 55, 55, 0.2);text-align:left;'>\n" +
            "<table style='width:100%;font-weight:300;margin-bottom:10px;border-collapse:collapse;text-align:left;'>\n" +
            "<tbody>\n" +
            "<tr style='font-weight:300'>\n" +
            "<td style='width:3.2%;max-width:30px;'></td>\n" +
            "<td style='max-width:480px;text-align:left;'>\n" +
            "<h1 id='cTMail-title' style='font-size: 20px; line-height: 36px; margin: 0px 0px 22px;'>\n" +
            "#Re:"+blog.getTitle()+"\n" +
            "</h1>\n" +
            "<p id='cTMail-userName' style='font-size:14px;color:#333; line-height:24px; margin:0;'>\n" +
            ""+comment+"\n" +
            "</p>\n" +
            "<p class='cTMail-content' style='line-height: 24px; margin: 6px 0px 0px; overflow-wrap: break-word; word-break: break-all;'>\n" +
            "<span style='color: rgb(51, 51, 51); font-size: 14px;'>\n" +
            "评论者:<a href='"+ url +"' target='_blank'>"+ nickname +"</a>\n" +
            "</span>\n" +
            "</p>\n" +
            "<p class='cTMail-content' style='line-height: 24px; margin: 6px 0px 0px; overflow-wrap: break-word; word-break: break-all;'>\n" +
            "<span style='color: rgb(51, 51, 51); font-size: 14px;'>\n" +
            "<br>\n" +
            " URL:\n" +
            "<br>\n" +
            "<a href='"+webUrl+"' target='_blank' title='' style='color: rgb(0, 164, 255); text-decoration: none; word-break: break-all; overflow-wrap: normal; font-size: 14px;'>\n" +
            ""+ webUrl +"\n" +
            "</a>\n" +
            "</span>\n" +
            "</p>\n" +
            "\n" +
            "<dl style='font-size: 14px; color: rgb(51, 51, 51); line-height: 18px;'>\n" +
            "<dd style='margin: 0px 0px 6px; padding: 0px; font-size: 12px; line-height: 22px;'>\n" +
            "<p id='cTMail-sender' style='font-size: 14px; line-height: 26px; word-wrap: break-word; word-break: break-all; margin-top: 32px;'>\n" +
            "此致\n" +
            "<br>\n" +
            "<strong>博客运维团队</strong>\n" +
            "</p>\n" +
            "</dd>\n" +
            "</dl>\n" +
            "</td>\n" +
            "<td style='width:3.2%;max-width:30px;'></td>\n" +
            "</tr>\n" +
            "</tbody>\n" +
            "</table>\n" +
            "</div>\n" +
            "\n" +
            "<div id='cTMail-copy' style='text-align:center; font-size:12px; line-height:18px; color:#999'>\n" +
            "<table style='width:100%;font-weight:300;margin-bottom:10px;border-collapse:collapse'>\n" +
            "<tbody>\n" +
            "<tr style='font-weight:300'>\n" +
            "<td style='width:3.2%;max-width:30px;'></td>\n" +
            "<td style='max-width:540px;'>\n" +
            "<p style='text-align:center; margin:20px auto 14px auto;font-size:12px;color:#999;'>\n" +
            "此为系统邮件，请勿回复。\n" +
            "</p>\n" +
            "</td>\n" +
            "<td style='width:3.2%;max-width:30px;'></td>\n" +
            "</tr>\n" +
            "</tbody>\n" +
            "</table>\n" +
            "</div>\n" +
            "</td>\n" +
            "<td style='width:3%;max-width:30px;'></td>\n" +
            "</tr>\n" +
            "</tbody>\n" +
            "</table>\n" +
            "</div>\n" +
            "</div>\n" +
            "</span>\n" +
            "                </div>\n" +
            "            </div>\n" +
            "        </div>\n" +
            "    </includetail>\n" +
            "</div>";
            if(sysEmail != null && sysEmail.getStatus() == 1){
                SendEmail.aTest(sysEmail.getMailSmtp(),sysEmail.getMailPort(),addressee,sysEmail.getMailUser(),title,emailContent,sysEmail.getMailName(),sysEmail.getMailPwd());
                SysEmailLog sysEmailLog = new SysEmailLog();
                sysEmailLog.setSendMailUser(sysEmail.getMailUser());
                sysEmailLog.setSendMailName(sysEmail.getMailName());
                sysEmailLog.setSendComment(emailContent);
                sysEmailLog.setSendAddresseeEmail(addressee);
                sysEmailLog.setSendMailSmtp(sysEmail.getMailSmtp());
                sysEmailLog.setSendType("博客评论通知");
                sysEmailLog.setCreateTime(new Date());

                sysEmailLogDao.saveEmailLog(sysEmailLog);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    //存放迭代找出的所有子代的集合
    private List<Comment> tempReplys = new ArrayList<>();

    /**
     * @Description: 查询出子评论
     */
    private void combineChildren(List<Comment> childComments) {
        //判断是否有一级子回复
        if(childComments.size() > 0){
            //循环找出子评论的id
            for(Comment childComment : childComments){
                tempReplys.add(childComment);
                Long childId = childComment.getCommentid();
                //查询二级以及所有子集回复
                recursively(childId);
            }
        }
    }

    /**
     * @Description: 循环迭代找出子集回复
     */
    private void recursively(Long childId) {
        //根据子一级评论的id找到子二级评论
        List<Comment> replayComments = commentDao.findParentIdNotNull(childId);
        if(replayComments.size() > 0){
            for(Comment replayComment : replayComments){
                Long replayId = replayComment.getCommentid();
                tempReplys.add(replayComment);
                //循环迭代找出子集回复
                recursively(replayId);
            }
        }
    }



}
